const StateManager = require("../template")

function testStateManagerComplexScenarios() {
  console.log(
    "1. 复杂状态结构测试:",
    (() => {
      const stateManager = new StateManager({
        user: {
          profile: {
            name: 'test',
            age: 25,
            preferences: {
              theme: 'dark',
              lang: 'en'
            }
          },
          settings: {
            notifications: true,
            privacy: 'public'
          }
        },
        app: {
          data: [1, 2, 3],
          config: {
            version: '1.0.0',
            features: ['feature1', 'feature2']
          }
        }
      })
      
      // 复杂状态操作
      const userName = stateManager.getState('user.profile.name')
      const theme = stateManager.getState('user.profile.preferences.theme')
      const data = stateManager.getState('app.data')
      const version = stateManager.getState('app.config.version')
      
      return userName === 'test' &&
             theme === 'dark' &&
             data.length === 3 &&
             version === '1.0.0'
    })()
  )

  console.log(
    "2. 状态管理器动态负载测试:",
    (() => {
      const stateManager = new StateManager()
      
      // 动态负载测试
      const loadPatterns = [
        { operation: 'set', key: 'load1', value: 100 },
        { operation: 'get', key: 'load1' },
        { operation: 'set', key: 'load2', value: 200 },
        { operation: 'get', key: 'load2' },
        { operation: 'update', key: 'load1', value: 150 },
        { operation: 'get', key: 'load1' }
      ]
      
      let successCount = 0
      loadPatterns.forEach(pattern => {
        if (pattern.operation === 'set') {
          stateManager.setState(pattern.key, pattern.value)
          successCount++
        } else if (pattern.operation === 'get') {
          const value = stateManager.getState(pattern.key)
          if (value !== undefined) successCount++
        } else if (pattern.operation === 'update') {
          stateManager.updateState(pattern.key, () => pattern.value)
          successCount++
        }
      })
      
      return successCount === 6
    })()
  )

  console.log(
    "3. 状态管理器边界条件测试:",
    (() => {
      const stateManager = new StateManager()
      
      // 边界条件测试
      const boundaryTests = [
        () => stateManager.setState('', 'empty'), // 空键
        () => stateManager.setState('key', null), // null值
        () => stateManager.setState('key', undefined), // undefined值
        () => stateManager.getState('nonexistent'), // 不存在的键
        () => stateManager.updateState('nonexistent', (prev) => prev + 1), // 更新不存在的键
        () => stateManager.subscribe('nonexistent', () => {}) // 订阅不存在的键
      ]
      
      let successCount = 0
      boundaryTests.forEach(test => {
        try {
          test()
          successCount++
        } catch (error) {
          // 某些操作可能失败
        }
      })
      
      return successCount >= 3 // 至少3个操作成功
    })()
  )

  console.log(
    "4. 状态管理器错误恢复测试:",
    (() => {
      const stateManager = new StateManager()
      
      try {
        // 错误恢复测试
        stateManager.setState('error', 'initial')
        
        // 模拟错误
        try {
          stateManager.setState('error', () => {
            throw new Error('Test error')
          })
        } catch (error) {
          // 错误被捕获
        }
        
        // 验证状态恢复
        const value = stateManager.getState('error')
        return value === 'initial'
      } catch (error) {
        return false
      }
    })()
  )

  console.log(
    "5. 状态管理器内存管理测试:",
    (() => {
      const stateManager = new StateManager()
      
      // 内存管理测试
      const stateCount = 1000
      
      // 添加大量状态
      for (let i = 0; i < stateCount; i++) {
        stateManager.setState(`key${i}`, i)
      }
      
      const initialPaths = stateManager.getStatePaths()
      
      // 移除一半状态
      for (let i = 0; i < stateCount / 2; i++) {
        stateManager.setState(`key${i}`, undefined)
      }
      
      const finalPaths = stateManager.getStatePaths()
      
      return initialPaths.length === stateCount &&
             finalPaths.length <= stateCount
    })()
  )

  console.log(
    "6. 状态管理器并发操作测试:",
    (() => {
      const stateManager = new StateManager()
      
      // 并发操作测试
      const operations = [
        () => stateManager.setState('concurrent', 1),
        () => stateManager.getState('concurrent'),
        () => stateManager.setState('concurrent', 2),
        () => stateManager.getState('concurrent'),
        () => stateManager.updateState('concurrent', (prev) => prev + 1),
        () => stateManager.getState('concurrent')
      ]
      
      operations.forEach(op => op())
      
      // 验证并发操作结果
      const finalValue = stateManager.getState('concurrent')
      
      return finalValue === 3
    })()
  )

  console.log(
    "7. 状态管理器复杂查询测试:",
    (() => {
      const stateManager = new StateManager({
        a: { b: { c: 1 } },
        d: { e: { f: 2 } },
        g: { h: { i: 3 } }
      })
      
      // 复杂查询测试
      const queries = [
        { path: 'a.b.c', expected: 1 },
        { path: 'd.e.f', expected: 2 },
        { path: 'g.h.i', expected: 3 },
        { path: 'a.b', expected: { c: 1 } },
        { path: 'd.e', expected: { f: 2 } }
      ]
      
      const results = queries.map(query => {
        const result = stateManager.getState(query.path)
        return JSON.stringify(result) === JSON.stringify(query.expected)
      })
      
      return results.every(result => result === true)
    })()
  )

  console.log(
    "8. 状态管理器状态一致性测试:",
    (() => {
      const stateManager = new StateManager()
      
      // 状态一致性测试
      const operations = [
        () => stateManager.setState('consistency', 1),
        () => stateManager.getState('consistency'),
        () => stateManager.updateState('consistency', (prev) => prev + 1),
        () => stateManager.getState('consistency'),
        () => stateManager.setState('consistency', 5),
        () => stateManager.getState('consistency')
      ]
      
      const results = operations.map(op => op())
      
      return results[1] === 1 && // 设置后获取
             results[3] === 2 && // 更新后获取
             results[5] === 5 // 重新设置后获取
    })()
  )

  console.log(
    "9. this上下文复杂场景测试:",
    (() => {
      const complexObj = {
        multiplier: 3,
        processComplex: function(data) {
          const stateManager = new StateManager({ data: data })
          stateManager.setState('data', data * this.multiplier)
          return stateManager.getState('data')
        }
      }
      
      return complexObj.processComplex(5) === 15
    })()
  )

  console.log(
    "10. 复杂对象this绑定复杂场景测试:",
    (() => {
      const complexConfigObj = {
        config: { threshold: 3 },
        processWithConfig: function(data) {
          const stateManager = new StateManager({ data: data })
          return stateManager.getState('data') >= this.config.threshold
        }
      }
      
      return complexConfigObj.processWithConfig(5) === true
    })()
  )

  console.log(
    "11. 状态管理器复杂操作序列测试:",
    (() => {
      const stateManager = new StateManager()
      
      // 复杂操作序列
      const operationSequence = [
        { op: 'set', key: 'seq1', value: 1 },
        { op: 'set', key: 'seq2', value: 2 },
        { op: 'get', key: 'seq1' },
        { op: 'update', key: 'seq1', value: 3 },
        { op: 'get', key: 'seq2' },
        { op: 'set', key: 'seq3', value: 4 },
        { op: 'get', key: 'seq3' }
      ]
      
      let successCount = 0
      operationSequence.forEach(seq => {
        try {
          if (seq.op === 'set') {
            stateManager.setState(seq.key, seq.value)
          } else if (seq.op === 'get') {
            const value = stateManager.getState(seq.key)
            if (value !== undefined) successCount++
          } else if (seq.op === 'update') {
            stateManager.updateState(seq.key, () => seq.value)
          }
          successCount++
        } catch (error) {
          // 某些操作可能失败
        }
      })
      
      return successCount >= 5 // 至少5个操作成功
    })()
  )

  console.log(
    "12. 状态管理器复杂场景综合测试:",
    (() => {
      const stateManager = new StateManager()
      
      // 综合复杂场景
      const scenarios = [
        // 场景1: 大量状态设置
        () => {
          for (let i = 0; i < 100; i++) {
            stateManager.setState(`scenario${i}`, i)
          }
          return stateManager.getStatePaths().length >= 100
        },
        // 场景2: 状态更新
        () => {
          stateManager.updateState('scenario0', (prev) => prev + 100)
          return stateManager.getState('scenario0') === 100
        },
        // 场景3: 状态订阅
        () => {
          let notified = false
          stateManager.subscribe('scenario1', () => {
            notified = true
          })
          stateManager.setState('scenario1', 200)
          return notified === true
        },
        // 场景4: 状态快照
        () => {
          const snapshot = stateManager.getSnapshot()
          stateManager.setState('scenario2', 300)
          stateManager.restoreSnapshot(snapshot)
          return stateManager.getState('scenario2') === 2
        },
        // 场景5: 最终验证
        () => {
          const totalPaths = stateManager.getStatePaths().length
          return totalPaths >= 100
        }
      ]
      
      const results = scenarios.map(scenario => scenario())
      
      return results.every(result => result === true)
    })()
  )
}

testStateManagerComplexScenarios()
